package org.example.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.example.pojo.Target;
import org.example.service.TargetService;
import org.example.util.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: Edward
 * @Date:2022-08-31 15:54
 * @subject:
 * 这个类负责和前端连接
 * 注入service，调用service的方法
 */
@Controller
@Api(tags = "targets测试")
@RequestMapping("/targets")
public class TargetController {
    //controller调用service层
    @Autowired
    private TargetService targetService;

    @ResponseBody
    @PostMapping("/targetWrite")
    @ApiOperation("编写月度目标")
    public ResponseData write(Target target){
        boolean b = targetService.addTarget(target);
        return b?ResponseData.getSccesss("编写成功",100):ResponseData.error("编写失败", 101);
    }

    @ResponseBody
    @PostMapping("/targetUpdate")
    @ApiOperation("修改月度目标")
    public ResponseData update(Target target){
        boolean b = targetService.updateTarget(target);
        return b?ResponseData.getSccesss("修改成功",100):ResponseData.error("修改失败", 101);
    }

    @ResponseBody
    @PostMapping("/targetDelete")
    @ApiOperation("通过id删除月度目标")
    public ResponseData delete(Integer tId){
        boolean b = targetService.deleteTargetById(tId);
        return b?ResponseData.getSccesss("删除成功",100):ResponseData.error("删除失败", 101);
    }

    @ResponseBody
    @GetMapping("/allTarget/{page}/{limit}")
    @ApiOperation("查询所有的用户并分页")
    public ResponseData list(@ApiParam("当前页") @PathVariable int page,@ApiParam("每一页的数据") @PathVariable int limit){

        PageHelper.startPage(page,limit);
        List<Target> targets = targetService.showAllTarget();
        PageInfo<Target> targetPageInfo = new PageInfo<>(targets);
        //以json的格式传递
        ResponseData jsonData = ResponseData.getJsonData(targets, (int) targetPageInfo.getTotal());
        return jsonData;
    }

    @ResponseBody
    @PostMapping("/targetSelect/{page}/{limit}/{t_name}")
    @ApiOperation("根据关键字对月度目标进行模糊查询")
    public ResponseData select(@ApiParam("当前页") @PathVariable int page,@ApiParam("每一页的数据") @PathVariable int limit,String tName){
        PageHelper.startPage(page,limit);
        List<Target> targets = targetService.selectTargetByName(tName);
        PageInfo<Target> targetPageInfo = new PageInfo<>(targets);
        //以json的格式传递
        ResponseData jsonData = ResponseData.getJsonData(targets, (int) targetPageInfo.getTotal());
        return jsonData;
    }
}
